package ui.activity.mine;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.dispatchapp.andlei.R;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.util.List;
import java.util.Map;

import application.App;
import base.BaseBean;
import base.activity.BaseLayoutActivity;
import bean.FileUploadEntity;
import bean.ResponseEntity;
import netWork.NetUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utils.DensityUtil;
import utils.GlideUtils;
import widget.ShopStatusPopupWindow;

/**
 * s身份认证 - 上传图片
 *
 * @author Andlei
 * @DATE 2019/1/23
 */
public class IdentityImageActivty extends BaseLayoutActivity {
    private NetUtils netUtils;
    private ImageView img_renzhengone, img_renzhengtwo;
    private Button btn_send;
    private int type;
    private String img1, img2;
    private ShopStatusPopupWindow pop;//,pop2;
    private List<LocalMedia> selectList;
    private ZLoadingDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("身份认证", true);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_identity_image;
    }

    @Override
    protected void findViews() {
        dialog = new ZLoadingDialog(mActivity);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
//                .setLoadingColor(Color.RED)//颜色
                .setHintText("上传中...")
//                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#CCCCCC"))  // 设置字体颜色
//                .setDurationTime(0.5) // 设置动画时间百分比 - 0.5倍
                .setDialogBackgroundColor(Color.parseColor("#00000000")); // 设置背景色，默认白色
        netUtils = new NetUtils(mActivity, netRequestCallBack);
        img_renzhengone = getView(R.id.img_renzhengone);
        img_renzhengtwo = getView(R.id.img_renzhengtwo);
        btn_send = getView(R.id.btn_send);
    }

    @Override
    protected void formatViews() {
        // 设置是否裁剪图片
        img_renzhengone.setOnClickListener(this);
        img_renzhengtwo.setOnClickListener(this);
        btn_send.setOnClickListener(this);
    }

    @Override
    protected void formatData() {

    }

    @Override
    protected void getBundle(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_renzhengone:
                type = 1;
                PictureSelector.create(IdentityImageActivty.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.img_renzhengtwo:
                type = 2;
                PictureSelector.create(IdentityImageActivty.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.btn_send:
                Intent intent = new Intent();
                intent.putExtra("img1", img1);
                intent.putExtra("img2", img2);
                setResult(12, intent);
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //  imagePicker.onActivityResult(mActivity, requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    dialog.show();
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //本地文件
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String savepath = getApplicationContext().getFilesDir().getAbsolutePath()+"/save.jpg";
                                    //Environment.getExternalStorageDirectory().getAbsolutePath() +"/save.jpg";
                            boolean result = GlideUtils.compressBitmap(selectList.get(0).getPath(),800, savepath);
                                    //compressImage(selectList.get(0).getPath(),savepath);
                                   // compressBitmap(selectList.get(0).getPath(),500, savepath);
                            try {
                                Thread.sleep(1500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if(result){
                                netUtils.uploadImg(savepath, new Callback<ResponseEntity<FileUploadEntity>>() {

                                    @Override
                                    public void onResponse(Call<ResponseEntity<FileUploadEntity>> call, Response<ResponseEntity<FileUploadEntity>> response) {
                                        dialog.dismiss();

                                        if (response.isSuccessful()) {
                                            if (response.body().getOk() == 1) {
                                                if (type == 2) {
                                                    GlideUtils.loadImageViewLodingSize(App.getInstance(), selectList.get(0).getPath(), DensityUtil.dip2px(App.getInstance(), 155), DensityUtil.dip2px(mActivity, 155), img_renzhengtwo, R.mipmap.img_renzhengone, R.mipmap.img_renzhengone);
                                                    img2 = response.body().getData().getSmall_img_url();
                                                } else {
                                                    GlideUtils.loadImageViewLodingSize(App.getInstance(), selectList.get(0).getPath(), DensityUtil.dip2px(App.getInstance(), 155), DensityUtil.dip2px(mActivity, 155), img_renzhengone, R.mipmap.img_renzhengone, R.mipmap.img_renzhengone);
                                                    img1 = response.body().getData().getSmall_img_url();
                                                }
                                            } else {
                                                toast("上传图片失败,请换张图片试试！");
                                            }
                                        } else {
                                            toast("图片异常，请换张图片试试！");
                                        }

                                    }

                                    @Override
                                    public void onFailure(Call<ResponseEntity<FileUploadEntity>> call, Throwable t) {
                                        dialog.dismiss();
                                        toast("上传图片失败,请重新上传");
                                    }
                                }, true);
                            }else {
                                toast("图片压缩失败");
                            }
                        }
                    }).start();

                    break;
            }
        }
    }

    private NetUtils.NetRequestCallBack netRequestCallBack = new NetUtils.NetRequestCallBack() {
        @Override
        public void error(String action, Throwable e, Map tag) {

        }

        @Override
        public void success(String action, BaseBean t, Map tag) {

        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }
}
